<?php
set_time_limit(0);

if ($MUSIC_DIR) $dir = $MUSIC_DIR; 
else $dir = '/var/music/';

$incomingDir = $dir.'INCOMING/';
$outgoingDir = $dir.'UNSORTED/';

function sortTrk ($trkList) {
   $i=0;
   $j=0;
   $k=0;
   $albList = array();
   $albIdList = array();
   if ($trkList) {
      foreach ($trkList as $trkSingle) {
         $albListKey = array_search(strtolower($trkSingle[album]), $albList);
         if ($albListKey !== false) {
            $trkSingle[albKey] = $albListKey;
            if ($albIdList[$albListKey]) $trkSingle[albId] = $albIdList[$albListKey];
         } else {
            $trkSingle[albKey] = $i;
            $albList[$i] = strtolower($trkSingle[album]);
            if ($albId = findAlbMatch($trkSingle)) { 
               $trkSingle[albId] = $albId;
               $albIdList[$i] = $albId;
            } else {
               $trkSingle[albId] = 'n'.$k;
               $albIdList[$i] = 'n'.$k;
               $k++;
            }
            $i++;
         }
         $trk[$j++] = $trkSingle;
      }
   }
   return $trk;
}

function findAlbMatch ($trk) {
   $albQuery = mysql_query("SELECT `cddbid`,`artist`,`is_comp`,`category` FROM `album` WHERE (LOWER(`title`) LIKE '".mysql_real_escape_string(strtolower($trk[album]))."') ") or die(mysql_error());
   while ($dbAlb = mysql_fetch_array($albQuery)) {
      if (str_replace('&', 'and', trim(strtolower($dbAlb[artist]))) == str_replace('&', 'and', trim(strtolower($trk[artist])))) {
         $match = true;
         return $dbAlb[cddbid];
      } else if ($dbAlb[is_comp]) {
         $match = true;
         return $dbAlb[cddbid];         
      }
   }
   if (!$match) return false;
}

if ($do === 'scanFiles') {
   
   
   // include the "loading..." widget
   include('./widgets/loading1.inc');
   
   $file = array();
   $file = getDirFiles ($incomingDir);
   
   if (empty($file)) echo('Sorry, it seems there were no files in the incoming folder.  Nothing was scanned.<br /><br />');
   
   $i=0;
   foreach ($file as $file) {
      if ($trkInfo = getTrkId3($file)) { 
         $trk[$i] = $trkInfo;
         $newFilename = mvTrkFile($trk[$i][filepath].'/'.$trk[$i][filename], $trk[$i], $MUSIC_DIR);
         $trk[$i][filepath] = $newFilename[filepath];
         $trk[$i][filename] = $newFilename[filename];
         $i++;
      }
   }
   rmEmpty($MUSIC_DIR.'INCOMING/', $MUSIC_DIR.'INCOMING/');
   
   $albList = sortTrk ($trk);
   $newAlbDbList = array(); // array for mock album-ids for new CDs
   $newAlbDbIdList = array(); // array for actual album IDs for CDs once they've been added. 
   $j=0; // iterator for newAlbDbIdList and newAlbDbList
   $l=0; // iterator for adding tracks to existing albums 
   $albIdList = array(); // array for all collected album Ids, to scan later to discover comps.
   for ($i=0; $i<count($albList); $i++) {
      if ($albList[$i][filepath] && $albList[$i][filename]) {
         if ($albList[$i][albId][0] === 'n') {  // this should match any album not already in the DB
            
            $newAlbKey = array_search($albList[$i][albId], $newAlbDbList);
            
            if ($newAlbKey === false) {  // if we haven't already created the CD, we should do so now.
               //insert both new alb and new track into db
               mysql_query(" 
                  INSERT INTO `album` SET 
                  `title`='".mysql_real_escape_string($albList[$i][album])."',
                  `artist`='".mysql_real_escape_string($albList[$i][artist])."',
                  `in_date`='".date('Y-m-d')."',
                  `status`='1'
               ");
               $newAlbDbList[$j] = $albList[$i][albId];
               $newAlbDbIdList[$j] = mysql_insert_id();
               
                mysql_query(" 
                  INSERT INTO `track` SET 
                  `cddbid`='".$newAlbDbIdList[$j]."',
                  `title`='".mysql_real_escape_string($albList[$i][title])."',
                  `artist`='".mysql_real_escape_string($albList[$i][artist])."',
                  `trackno`='".mysql_real_escape_string($albList[$i][num])."',
                  `time`='".$albList[$i][playtime]."',
                  `filepath`='".mysql_real_escape_string($albList[$i][filepath])."',
                  `filename`='".mysql_real_escape_string($albList[$i][filename])."'
               ");
               $j++;
            } else {
               mysql_query("
                  INSERT INTO `track` SET
                  `cddbid`='".$newAlbDbIdList[$newAlbKey]."',
                  `title`='".mysql_real_escape_string($albList[$i][title])."',
                  `artist`='".mysql_real_escape_string($albList[$i][artist])."',
                  `trackno`='".mysql_real_escape_string($albList[$i][num])."',
                  `time`='".$albList[$i][playtime]."',
                  `filepath`='".mysql_real_escape_string($albList[$i][filepath])."',
                  `filename`='".mysql_real_escape_string($albList[$i][filename])."'
               ");
            }
         } else if (ctype_digit($albList[$i][albId])) {
            if (!in_array($albList[$i][albId], $albIdList)) $albIdList[$l++] = $albList[$i][albId];
            mysql_query("
               INSERT INTO `track` SET
               `cddbid`='".$albList[$i][albId]."',
               `title`='".mysql_real_escape_string($albList[$i][title])."',
               `artist`='".mysql_real_escape_string($albList[$i][artist])."',
               `trackno`='".mysql_real_escape_string($albList[$i][num])."',
               `time`='".$albList[$i][playtime]."',
               `filepath`='".mysql_real_escape_string($albList[$i][filepath])."',
               `filename`='".mysql_real_escape_string($albList[$i][filename])."'
            ");
         }
      }
   }
   if ($newAlbDbIdList && !empty($newAlbDbIdList)) {
      foreach ($newAlbDbIdList as $newAlb) {
         $chkComp = mysql_result(mysql_query("SELECT COUNT(DISTINCT(LOWER(`artist`))) FROM `track` WHERE (`cddbid`='".$newAlb."') "), 0);
         if ($chkComp > 1) mysql_query(" UPDATE `album` SET `is_comp`='1',`artist`='Various' WHERE `cddbid`='".$newAlb."'");
      }
   }
   
   if ($newAlbDbIdList && !empty($newAlbDbIdList)) {
      echo('<h3>These albums were added anew:</h3><ul>');
      foreach ($newAlbDbIdList as $newAlb) {
         $addAlbQuery = mysql_query(" SELECT * FROM `album` WHERE `cddbid`='".$newAlb."' LIMIT 1 ");
         $alb = mysql_fetch_array($addAlbQuery);
         if ($alb[is_comp] == 1) $isComp = ' (as comp.)';
         else $isComp = '';
         printf('<li><i><a href="?mode=cdedit&albId=%s">%s</a></i> by %s</li> %s', $alb[cddbid], $alb[title], $alb[artist], $isComp);
      }
      echo('</ul>');
   }
   if ($albIdList && !empty($albIdList)) {
      echo('<br /><h3>These existing albums had tracks added:</h3><ul>');
      foreach ($albIdList as $newAlb) {
         $addAlbQuery = mysql_query(" SELECT * FROM `album` WHERE `cddbid`='".$newAlb."' LIMIT 1 ");
         $alb = mysql_fetch_array($addAlbQuery);
//         if ($alb[is_comp]) $isComp = ' (as comp.)';
         printf('<li><i><a href="?mode=cdedit&albId=%s">%s</a></i> by %s</li>', $alb[cddbid], $alb[title], $alb[artist]);
      }
      echo('</ul>');
   }
   
   
   // include the "loading..." widget shutoff trigger 
   include ('./widgets/loading2.inc');
   
}

?>
<form method="post">
Enter Folder:<br>
(use forward slashes and make sure you have a trailing slash on the end ex: c:/path/to/files/ )<br>
<input type="text" name="rootDir"><br>
<input type="hidden" name"loading" value="true" />
<input type="submit" value="scan files into DB">
<input type="hidden" name="do" value="scanFiles" /></form>
<?php
// }
?>